<template>
	<view class="homework-container">
		<!-- 标题栏 -->
		<view class="homework-header">
			<text>AI智能作业题目生成</text>
		</view>
		
		<!-- 加载提示 -->
		<view v-if="loading" class="loading-container">
			<text>正在生成题目，请稍候...</text>
		</view>
		
		<!-- 题目显示区域（非作业模式） -->
		<scroll-view v-else-if="questions.length > 0 && !homeworkMode" class="questions-container" scroll-y="true">
			<view class="topic-name">
				<text>作业：{{ topicName }}</text>
			</view>
			
			<!-- 开始作业按钮 -->
			<view class="start-homework-container">
				<button class="start-homework-btn" @click="startHomework">开始作业</button>
			</view>
			
			<view v-for="(question, index) in questions" :key="index" class="question-item">
				<view class="question-header">
					<text class="question-number">题目 {{ index + 1 }}</text>
					<text class="question-type">{{ question.type }}</text>
				</view>
				<view class="question-content">
					<text>{{ question.content }}</text>
				</view>
				<view v-if="question.options" class="question-options">
					<view v-for="(option, optIndex) in question.options" :key="optIndex" class="option-item">
						<text>{{ optionLabels[optIndex] }}. {{ option }}</text>
					</view>
				</view>
				<view class="question-answer">
					<text class="answer-label">参考答案：</text>
					<text>{{ question.answer }}</text>
				</view>
			</view>
		</scroll-view>
		
		<!-- 作业模式 -->
		<scroll-view v-else-if="homeworkMode" class="questions-container" scroll-y="true">
			<view class="topic-name">
				<text>作业：{{ topicName }}</text>
				<text class="homework-score" v-if="homeworkFinished">得分：{{ homeworkScore }}/{{ questions.length }}</text>
			</view>
			
			<!-- 作业控制按钮 -->
			<view class="homework-controls">
				<button v-if="!homeworkFinished" class="submit-homework-btn" @click="submitHomework">提交答案</button>
				<button v-else class="return-btn" @click="returnToQuestions">返回题目列表</button>
			</view>
			
			<view v-for="(question, index) in questions" :key="index" class="question-item">
				<view class="question-header">
					<text class="question-number">题目 {{ index + 1 }}</text>
					<text class="question-type">{{ question.type }}</text>
				</view>
				<view class="question-content">
					<text>{{ question.content }}</text>
				</view>
				
				<!-- 选择题选项（作业模式） -->
				<view v-if="question.options" class="question-options homework-options">
					<view 
						v-for="(option, optIndex) in question.options" 
						:key="optIndex" 
						:class="['option-item', 'homework-option', 
							{
								'selected': userAnswers[index] === optionLabels[optIndex],
								'correct': homeworkFinished && question.answer === optionLabels[optIndex],
								'incorrect': homeworkFinished && userAnswers[index] === optionLabels[optIndex] && question.answer !== optionLabels[optIndex]
							}
						]"
						@click="selectAnswer(index, optionLabels[optIndex])"
					>
						<text>{{ optionLabels[optIndex] }}. {{ option }}</text>
					</view>
				</view>
				
				<!-- 答案反馈（作业模式） -->
				<view v-if="homeworkFinished && userAnswers[index]" class="answer-feedback">
					<view v-if="userAnswers[index] === question.answer" class="correct-answer">
						<text>✓ 回答正确</text>
					</view>
					<view v-else class="incorrect-answer">
						<text>✗ 回答错误</text>
						<text class="correct-answer-text">正确答案: {{ question.answer }}</text>
					</view>
				</view>
			</view>
		</scroll-view>
		
		<!-- 空状态提示 -->
		<view v-else class="empty-container">
			<text>请等待作业题目生成</text>
		</view>
	</view>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useUserStore } from '@/stores/api.js';

const userStore = useUserStore();

const topicName = ref('');
const loading = ref(false);
const questions = ref([]);
const optionLabels = ['A', 'B', 'C', 'D', 'E', 'F'];

// 作业相关状态
const homeworkMode = ref(false);
const homeworkFinished = ref(false);
const userAnswers = ref({});
const homeworkScore = ref(0);

// 封装答题结果,只包含用户信息和答题结果（题目和正确性）
const jieguo = ref({
	// 答题用户
	user: '',
	userId: 0,
	fenshu: 0,
	maxfenshu: 0,
	topic: '',
	// 存储答题结果（题目编号和是否答题正确）
	results: {}
});

// 生成题目的方法
const generateQuestions = async (description) => {
	loading.value = true;
	questions.value = [];
	topicName.value = description || '未知主题';
	
	try {
		// 发送请求到后端AI接口
		const res = await uni.request({
			url: 'http://127.0.0.1:8081/ai/chat',
			method: 'POST',
			data: {
				message: `请根据主题"${description || '通用知识'}"生成5道作业题目，只包含单选题，并提供参考答案,参考答案只返回ABCD即可。请按以下JSON格式返回：[{"type":"单选题","content":"题目内容","options":["选项A","选项B","选项C","选项D"],"answer":"参考答案"}]`
			},
			header: {
				'Content-Type': 'application/json'
			}
		});

		console.log("作业题目生成结果:", res);
		
		// 处理返回的题目数据
		if (res.data) {
			try {
				// 尝试从返回的文本中提取JSON部分
				const textResponse = typeof res.data === 'string' ? res.data : JSON.stringify(res.data);
				const jsonMatch = textResponse.match(/\[\s*\{.*\}\s*\]/s);
				
				if (jsonMatch) {
					// 提取到了JSON格式的字符串
					const jsonStr = jsonMatch[0];
					const parsedData = JSON.parse(jsonStr);
					questions.value = Array.isArray(parsedData) ? parsedData : [parsedData];
				} else {
					// 没有找到JSON格式，将文本作为一个题目处理
					questions.value = [{
						type: '文本题目',
						content: textResponse,
						answer: '请参考内容自行解答'
					}];
				}
			} catch (parseError) {
				console.error('解析题目数据失败:', parseError);
				// 解析失败，将原始文本作为内容显示
				const textResponse = typeof res.data === 'string' ? res.data : JSON.stringify(res.data);
				questions.value = [{
					type: '文本题目',
					content: textResponse,
					answer: '请参考内容自行解答'
				}];
			}
		} else {
			uni.showToast({
				title: '生成题目失败，请重试',
				icon: 'none'
			});
		}
	} catch (error) {
		console.error('请求出错:', error);
		uni.showToast({
			title: '网络请求失败，请检查网络连接',
			icon: 'none'
		});
	} finally {
		loading.value = false;
	}
	console.log("生成的作业题目:", questions.value);
};

// 开始作业
const startHomework = () => {
	// 重置作业状态
	homeworkMode.value = true;
	homeworkFinished.value = false;
	userAnswers.value = {};
	homeworkScore.value = 0;
	
	uni.showToast({
		title: '作业开始，请选择答案',
		icon: 'none'
	});
};

// 选择答案
const selectAnswer = (questionIndex, answer) => {
	if (!homeworkFinished.value) {
		userAnswers.value[questionIndex] = answer;
	}
};

// 提交作业答案
const submitHomework = () => {
	// 检查是否所有题目都已回答
	const answeredCount = Object.keys(userAnswers.value).length;
	if (answeredCount < questions.value.length) {
		uni.showModal({
			title: '提示',
			content: `您还有 ${questions.value.length - answeredCount} 道题目未回答，确定要提交吗？`,
			success: (res) => {
				if (res.confirm) {
					finishHomework();
				}
			}
		});
	} else {
		finishHomework();
	}
};

// 完成作业并计算得分
const finishHomework = () => {
	homeworkFinished.value = true;
	let correctCount = 0;
	
	// 计算得分并封装答题结果
	jieguo.value.results = {}; // 清空之前的结果
	jieguo.value.user = userStore.getUserName || 'student';
	jieguo.value.userId = userStore.getUserId || 0;
	jieguo.value.topic = topicName.value;
	
	questions.value.forEach((question, index) => {
		const isCorrect = userAnswers.value[index] === question.answer;
		if (isCorrect) {
			correctCount++;
		}
		
		// 简化的答题结果，只包含题目编号和是否正确
		jieguo.value.results[index] = {
			questionNumber: index + 1,
			isCorrect: isCorrect
		};
	});
	
	homeworkScore.value = correctCount;
	jieguo.value.fenshu = correctCount;
	jieguo.value.maxfenshu = questions.value.length;
	
	// 发送答题结果到后端
	sendResultsToBackend();
	
	uni.showToast({
		title: `作业完成，得分：${correctCount}/${questions.value.length}`,
		icon: 'none',
		duration: 2000
	});
};

// 发送答题结果到后端
const sendResultsToBackend = () => {
	console.log('发送作业结果到后端:', jieguo.value);
	
	uni.request({
		url: 'http://localhost:8088/UserAppLogin/homework', // 后端接收作业结果的接口，根据实际情况修改
		method: 'POST',
		data: jieguo.value,
		header: {
			'Content-Type': 'application/json'
		},
		success: (res) => {
			console.log('作业结果提交成功:', res);
			uni.showToast({
				title: '作业结果已提交',
				icon: 'success'
			});
		},
		fail: (err) => {
			console.error('作业结果提交失败:', err);
			uni.showToast({
				title: '作业结果提交失败',
				icon: 'none'
			});
		}
	});
};

// 返回题目列表
const returnToQuestions = () => {
	homeworkMode.value = false;
	homeworkFinished.value = false;
};

// 页面加载时从参数中获取description并生成题目
onLoad((options) => {
	console.log('作业页面参数:', options);
	if (options && options.description) {
		// 使用options中的description作为关键字生成作业题
		generateQuestions(options.description);
	}
});
</script>

<style>
.homework-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	padding: 10px;
	box-sizing: border-box;
}

.homework-header {
	text-align: center;
	padding: 15px 0;
	font-weight: bold;
	font-size: 18px;
	border-bottom: 1px solid #eee;
}

.loading-container,
.empty-container {
	display: flex;
	justify-content: center;
	align-items: center;
	flex: 1;
	padding: 20px;
	color: #999;
}

.questions-container {
	flex: 1;
	padding: 10px;
	overflow-y: auto;
}

.topic-name {
	padding: 10px;
	font-size: 16px;
	font-weight: bold;
	color: #333;
	background-color: #f8f8f8;
	border-radius: 5px;
	margin-bottom: 15px;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.homework-score {
	color: #ff6b6b;
	font-size: 14px;
}

.start-homework-container {
	display: flex;
	justify-content: center;
	margin-bottom: 20px;
}

.start-homework-btn {
	background-color: #07c871;
	color: white;
	padding: 10px 30px;
	border-radius: 5px;
	font-size: 16px;
}

.homework-controls {
	display: flex;
	justify-content: center;
	margin-bottom: 20px;
}

.submit-homework-btn {
	background-color: #e74c3c;
	color: white;
	padding: 10px 30px;
	border-radius: 5px;
	font-size: 16px;
}

.return-btn {
	background-color: #7f8c8d;
	color: white;
	padding: 10px 30px;
	border-radius: 5px;
	font-size: 16px;
}

.question-item {
	margin-bottom: 20px;
	padding: 15px;
	background-color: #fff;
	border-radius: 8px;
	box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.question-header {
	display: flex;
	justify-content: space-between;
	margin-bottom: 10px;
}

.question-number {
	font-weight: bold;
	color: #07c160;
}

.question-type {
	color: #666;
	font-size: 14px;
}

.question-content {
	margin-bottom: 10px;
	line-height: 1.5;
}

.question-options {
	margin-bottom: 10px;
}

.option-item {
	margin-bottom: 5px;
	padding-left: 10px;
}

.homework-options .homework-option {
	padding: 8px 10px;
	border-radius: 5px;
	border: 1px solid #ddd;
	margin-bottom: 8px;
	cursor: pointer;
}

.homework-options .selected {
	background-color: #e3f2fd;
	border-color: #2196f3;
}

.homework-options .correct {
	background-color: #e8f5e9;
	border-color: #4caf50;
}

.homework-options .incorrect {
	background-color: #ffebee;
	border-color: #f44336;
}

.answer-feedback {
	margin-top: 10px;
	padding: 10px;
	border-radius: 5px;
}

.correct-answer {
	color: #4caf50;
	font-weight: bold;
}

.incorrect-answer {
	color: #f44336;
	font-weight: bold;
}

.correct-answer-text {
	display: block;
	margin-top: 5px;
	color: #4caf50;
	font-weight: normal;
}

.question-answer {
	margin-top: 10px;
	padding-top: 10px;
	border-top: 1px dashed #eee;
}

.answer-label {
	color: #ff6b6b;
	font-weight: bold;
	margin-right: 5px;
}
</style>
